﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeTemplate2.Mapper.Employee;
using CodeTemplate2.Models.Employee;
using CodeTemplate2.EmployeeService;

namespace CodeTemplate2.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListEmployee()
        {
            ListEmployeeModel model = new ListEmployeeModel();      
            SetupListViewModel(model);
            if (Request.QueryString["Sort"] != null)
            {
                GetAllResponseModel temp = Search(new GetAllRequestModel()
                {
                    EmpId = "",
                    Name = "",
                    Status = 0,
                    Sort = "EmpId",
                    SortType = sType.ASC
                });
                model.ListOfEmployee = temp.EmpList;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult ListEmployee(string submitButton, string[] checkbox, ListEmployeeModel input)
        {
            if (ModelState.IsValid)
            {
               switch(submitButton) {
                   case "Search" :
                        input.ListOfEmployee = PrepareSearch(input);                      
                        break;
                   case "Delete" :
                        input = Delete(checkbox, input);
                        break;
                   default :
                        break;
               }
            }
            SetupListViewModel(input);
            return View(input);
            
        }

        public ActionResult ViewDetail(String EmpId)
        {
            EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();

            GetAllRequestDto objGet = new GetAllRequestDto()
            {
                EmpId = EmpId
            };

            var list = service.GetAll(objGet);
            EmployeeModel resultModel = null;


            if (list.Data != null && list.Data.Count > 0)
			{
                EmployeeDto resultDto = list.Data[0];
                resultModel = EmployeeMapper.DtoToModel(resultDto);

                //Test
                resultModel.BirthDate = resultModel.BirthDate.AddYears(543);
			}
            SetupRegisterViewModel(resultModel);
            SetupBranchLookup(resultModel);
            return View(resultModel);
		}

        public ActionResult Update(EmployeeModel inputModel)
		{
            if (ModelState.IsValid)
            {
                EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
                service.Update(EmployeeMapper.ModelToDto(inputModel));
                return RedirectToAction("ListEmployee", "Employee");
            }
            else
            {
                SetupRegisterViewModel(inputModel);
                SetupBranchLookup(inputModel);
                return View("ViewDetail", inputModel);
            }
			
		}

        public ActionResult Add()
        {
            EmployeeModel model = new EmployeeModel();
            model.BirthDate = DateTime.Now.AddYears(543);
            SetupRegisterViewModel(model);
            return View(model);
        }

        [HttpPost]
        public ActionResult Add(EmployeeModel inputModel)
        {
            if (ModelState.IsValid)
            {
                EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
                service.Add(EmployeeMapper.ModelToDto(inputModel));
                return RedirectToAction("ListEmployee");
            }
            else
            {
                SetupRegisterViewModel(inputModel);
                return View(inputModel);
            }
           
        }

        [HttpPost]
        public ActionResult DeleteEmployees(string[] checkbox)
        {
            ListEmployeeModel input = new ListEmployeeModel();
            if (ModelState.IsValid)
            {
                input = Delete(checkbox, input);
            }

            SetupListViewModel(input);
            return View("ListEmployee", input);
        }

        [HttpPost]
        public String DeleteEmployeeById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
            service.Delete(delList);

			
			return "Success";

            //return RedirectToAction("ListEmployee");
        }

        // Check does empId exist
        [HttpPost]
        public JsonResult doesEmpIdExist(string EmpId, string Mode, string OldValue)
        {
            bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Equals(EmpId, StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
                GetAllResponseModel temp = Search(new GetAllRequestModel()
                {
                    EmpId = EmpId,
                    Name = "",
                    Status = 0,
                    Sort = "EmpId",
                    SortType = sType.ASC
                });
                return Json(temp.EmpList.Count == 0);
            }
            else
                return Json(true);
        }

        private void SetupRegisterViewModel(EmployeeModel model)
        {
            if (TempData["BindingJobtitle"] == null)
                TempData.Add("BindingJobtitle", new SelectList(JobTitleMapper.GetJobTitleForDDL(), "JobTitleId", "JobTitleName"));
            model.BindingJobtitle = (SelectList)TempData["BindingJobtitle"];
        }

        private void SetupListViewModel(ListEmployeeModel model)
        {
            model.BindingStatus = new SelectList(EmployeeMapper.GetEmployeeStatusForDDL(), "StatusId", "StatusName");
        }

        private void SetupBranchLookup(EmployeeModel model)
        {
            if (TempData["BindingBranch"] == null)
                TempData.Add("BindingBranch", BranchMapper.GetBranchAll());
            BranchModel bm = ((List<BranchModel>)TempData["BindingBranch"]).Find(item => item.Branch_id == model.Branch);
            if (bm != null)
            {
                model.BindingBranchCode = bm.Branch_code;
                model.BindingBranchName = bm.Branch_name;
            }
        }

        private ListEmployeeModel Delete(string[] inputList, ListEmployeeModel input)
        {
            List<string> delList = new List<string>();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
                var resEmp = service.Delete(delList);
            }

            input.ListOfEmployee = PrepareSearch(input);
            return input;
        }

        private List<EmployeeModel> PrepareSearch(ListEmployeeModel input)
        {

            GetAllRequestModel searchInputs = new GetAllRequestModel()
            {
                EmpId = (input.EmpIdSearch == null) ? "" : input.EmpIdSearch,
                Name = (input.NameSearch == null) ? "" : input.NameSearch,
                Status = (input.StatusSearch == 0) ? 0 : input.StatusSearch,
                Sort = "EmpId", SortType = sType.ASC
            };
            GetAllResponseModel result = Search(searchInputs);
            return result.EmpList;
        }

        private GetAllResponseModel Search(GetAllRequestModel input)
        {
            EmployeeServiceClient service = new EmployeeServiceClient();
            GetAllRequestDto gAllreq = new GetAllRequestDto
            { 
                 EmpId = input.EmpId,
                 Name = input.Name, 
                 Sort = input.Sort, 
                 SortType = input.SortType.ToString(),
                 Status = input.Status
            };
            var response = service.GetAll(gAllreq);
            GetAllResponseModel result = new GetAllResponseModel();
            result.EmpList = new List<EmployeeModel>();
            if(response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (EmployeeDto responseDTO in response.Data)
                    {
                        EmployeeModel resultModel = null;
                        EmployeeDto tempDto = responseDTO;
                        resultModel = EmployeeMapper.DtoToModel(tempDto);
                        result.EmpList.Add(resultModel);
                    }
                }
            }
            return result;
        }

        public String GetLookup()
        {
            EmployeeModel model = new EmployeeModel();
            if (Request.QueryString["searchKey"] != null)
            {
                List<BranchModel> Branch = BranchMapper.GetBranchForLookup(Request.QueryString["searchKey"]);
                if (Branch.Count == 1)
                {
                    String BranchStr;
                    foreach (var item in Branch)
                    {
                        BranchStr = String.Concat(item.Branch_id.ToString(), "|", item.Branch_code, "|", item.Branch_name);
                        return BranchStr;
                    }

                }
                else if (Branch.Count > 1)
                {
                    return "MoreOne";
                }
            }
            return "";
        }

        public ActionResult Popup()
        {
            BranchModel model = new BranchModel();
            if (Request.QueryString["searchKey"] != null)
            {
                model.ListOfBranch = BranchMapper.GetBranchForLookup(Request.QueryString["searchKey"]);
            }
            else
            {
                model.ListOfBranch = BranchMapper.GetBranchAll();
            }
            return View(model);
        }
    }
}
